package com.bkgy.controller.technology.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bkgy.controller.technology.entity.Cgl1870ProcessDatas;
import com.bkgy.controller.technology.entity.TTechParam;
import com.bkgy.controller.technology.mapper.ITechParamMapper;
import com.bkgy.controller.technology.service.ITechParamService;
import com.bkgy.sys.common.entity.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class TechParamServiceImpl extends ServiceImpl<ITechParamMapper, TTechParam> implements ITechParamService {
    @Override
    public void checkParam(Map<String, List<TTechParam>> paramMap, Cgl1870ProcessDatas d) {
//        1	碱洗温度
//        2	电解温度
//        3	漂洗温度
//        4	碱洗电导率
//        5	电解清洗电导率
//        6	漂洗电导率
//        7	反射率
//        9	锌液成分Al
//        10	锌液成分Fe
//        11	锌液温度
//        12	加湿器露点IF钢
//        13	加湿器露点加磷高强钢
//        14	气刀距离
//        15	气刀高度
//        16	光整延伸率
//        17	光整液浓度
//        18	涂油
        // 验证通用范围
        //碱喷电导率实际[μS/cm]
        d.setSprayCondActJudge(checkRange(d.getSprayCondActAvg(), paramMap.get("4").get(0)));
        //碱刷电导率实际[μS/cm]
        d.setBrushCondActJudge(checkRange(d.getBrushCondActAvg(), paramMap.get("4").get(0)));
        //清洗段碱喷循环槽温度[℃]
        d.setSprayTempJudge(checkRange(d.getSprayTempAvg(), paramMap.get("1").get(0)));
        //清洗段碱刷循环槽温度[℃]
        d.setBrushTempJudge(checkRange(d.getBrushTempAvg(), paramMap.get("1").get(0)));
        //清洗段电解循环槽温度[℃]
        d.setElecTempJudge(checkRange(d.getElecTempAvg(), paramMap.get("1").get(0)));
        //清洗段漂洗循环槽温度[℃]
        d.setRinseTempJudge(checkRange(d.getRinseTempAvg(), paramMap.get("3").get(0)));
        //电解电导率实际[μS/cm]
        d.setElecCondActJudge(checkRange(d.getElecCondActAvg(), paramMap.get("5").get(0)));
        //漂洗电导率实际[μS/cm]
        d.setRinseCondActJudge(checkRange(d.getRinseCondActAvg(), paramMap.get("6").get(0)));
        //光整液浓度
        d.setSpmLiquidConcJudge(checkRange(d.getSpmLiquidConcAvg(), paramMap.get("17").get(0)));
        //气刀距离（上表面）平均值
        d.setAirKnifeDisTopJudge(checkRange(d.getAirKnifeDisTopAvg(), paramMap.get("14").get(0)));
        //气刀距离（下表面）平均值
        d.setAirKnifeDisBtmJudge(checkRange(d.getAirKnifeDisBtmAvg(), paramMap.get("14").get(0)));
        //气刀高度（上表面）平均值
        d.setAirKnifeHighTopJudge(checkRange(d.getAirKnifeHighTopAvg(), paramMap.get("15").get(0)));
        //气刀高度（下表面）平均值
        d.setAirKnifeHighBtmJudge(checkRange(d.getAirKnifeHighBtmAvg(), paramMap.get("15").get(0)));
        //GI锌锅温度
        d.setGiZnpotTempJudge(checkRange(d.getGiZnpotTempAvg(), paramMap.get("11").get(0)));
        //GA锌锅温度
        d.setGaZnpotTempJudge(checkRange(d.getGaZnpotTempAvg(), paramMap.get("11").get(0)));
        //延伸率实际（spm el）
        d.setSpmElongActJudge(checkRange(d.getSpmElongActAvg(), paramMap.get("16").get(0)));
        //涂油重量，重设范围基础值，不适用库表的
        TTechParam param = paramMap.get("18").get(0);
        param.setBaseValue(d.getOilamount().divide(BigDecimal.TEN));
        d.setOilAmountStripJudge(checkRange(d.getOilAmountStripAvg(), param));

        //验证标志
        boolean flag = false;
        //验证连退指标列表比对
        String grade = d.getSteelgrade();
        if (paramMap.containsKey(grade) || paramMap.containsKey(grade+"/ZF")) {
            List<TTechParam> list = paramMap.get(d.getSteelgrade());
            if(list == null || list.size() == 0) {
                list = paramMap.get(grade+"/ZF");
            }
            for (TTechParam techParam : list) {
                String thickExec = techParam.getThickExec();
                //有厚度表达式（连退工艺指标）
                if (StringUtils.isNotEmpty(thickExec) && !"-1".equals(thickExec)) {
                    if (!thickExec.contains("t")) {
                        double v = Double.parseDouble(thickExec.substring(1));
                        if ((thickExec.startsWith("=") && d.getInMatThk().compareTo(new BigDecimal(v)) == 0) ||
                                (thickExec.startsWith("＞") && d.getInMatThk().compareTo(new BigDecimal(v)) > 0) ||
                                (thickExec.startsWith("≥") && d.getInMatThk().compareTo(new BigDecimal(v)) >= 0) ||
                                (thickExec.startsWith("＜") && d.getInMatThk().compareTo(new BigDecimal(v)) < 0) ||
                                (thickExec.startsWith("≤") && d.getInMatThk().compareTo(new BigDecimal(v)) <= 0)
                        ) {
                            flag = check4Param(techParam, d);
                        }
                    } else {
                        BigDecimal b1 = new BigDecimal(thickExec.substring(0, thickExec.indexOf("t") - 1));
                        BigDecimal b2 = new BigDecimal(thickExec.substring(thickExec.indexOf("t") + 2));
                        //操作符
                        String op1 = thickExec.substring(thickExec.indexOf("t") - 1, thickExec.indexOf("t"));
                        String op2 = thickExec.substring(thickExec.indexOf("t") + 1, thickExec.indexOf("t") + 2);
                        //命中范围
                        if ((("≤".equals(op1) && d.getInMatThk().compareTo(b1) >= 0) || ("＜".equals(op1) && d.getInMatThk().compareTo(b1) > 0))
                                && (("≤".equals(op2) && d.getInMatThk().compareTo(b2) <= 0) || ("＜".equals(op2) && d.getInMatThk().compareTo(b2) < 0))) {
                            flag = check4Param(techParam, d);
                        }
                    }
                } else {
                    flag = check4Param(techParam, d);
                }
            }
        }

        if (!flag) {
            log.warn("超出工艺指标范围");
        }
    }

    //验证基本范围
    @Override
    public int checkRange(BigDecimal baseParam, TTechParam techParam) {
        if(baseParam == null){
            return -1;
        }
        //检查非连续退火的范围符合度
        int flag = 0;
        String baseOffset = techParam.getBaseValueOffset();
        if (baseOffset.startsWith("±")) {
            double v = Double.parseDouble(baseOffset.substring(1));
            BigDecimal b1 = techParam.getBaseValue().subtract(BigDecimal.valueOf(v));
            BigDecimal b2 = techParam.getBaseValue().add(BigDecimal.valueOf(v));
            if (baseParam.compareTo(b1) < 0 || baseParam.compareTo(b2) > 0) {
                flag = 1;
            }
        } else if (baseOffset.startsWith("≥") || baseOffset.startsWith("＞") || baseOffset.startsWith("＜") || baseOffset.startsWith("≤")) {
            double v = Double.parseDouble(baseOffset.substring(1));
            String s = techParam.getBaseValue().compareTo(BigDecimal.ZERO) > 0 ? techParam.getBaseValue().toString() : "";
            if (baseOffset.startsWith("≥") && baseParam.compareTo(BigDecimal.valueOf(v)) < 0) {
                flag = 1;
            }
            if (baseOffset.startsWith("＞") && baseParam.compareTo(BigDecimal.valueOf(v)) <= 0) {
                flag = 1;
            }
            if (baseOffset.startsWith("＜") && baseParam.compareTo(BigDecimal.valueOf(v)) >= 0) {
                flag = 1;
            }
            if (baseOffset.startsWith("≤") && baseParam.compareTo(BigDecimal.valueOf(v)) > 0) {
                flag = 1;
            }
        }
        return flag;
    }

    //验证RTF、SCS、RCS、EQS
    private boolean check4Param(TTechParam techParam, Cgl1870ProcessDatas d) {
        //检查RTF指标符合度
        if (techParam.getRtf() != null && techParam.getRtf().compareTo(BigDecimal.ZERO) > 0) {
            if (d.getP5TempActAvg() != null) {
                //在±10范围内
                BigDecimal b1 = techParam.getRtf().subtract(BigDecimal.TEN);
                BigDecimal b2 = techParam.getRtf().add(BigDecimal.TEN);
                if (d.getP5TempActAvg().compareTo(b1) < 0 || d.getP5TempActAvg().compareTo(b2) > 0) {
                    d.setP6TempActJudge(1);
                }
            } else {
                //被检查指标为空
                log.warn("RTF/SF指标参数不存在");
            }
        }
        //检查SCS符合度
        if (techParam.getScs() != null && techParam.getScs().compareTo(BigDecimal.ZERO) > 0) {
            if (d.getScsStripTempActAvg() != null) {
                //在±20范围内
                BigDecimal b1 = techParam.getScs().subtract(BigDecimal.valueOf(20));
                BigDecimal b2 = techParam.getScs().add(BigDecimal.valueOf(20));
                if (d.getScsStripTempActAvg().compareTo(b1) < 0 || d.getScsStripTempActAvg().compareTo(b2) > 0) {
                    d.setScsStripTempActJudge(1);
                }
            } else {
                log.warn("SCS指标参数不存在");
            }
        }
        //检查RCS符合度
        if (techParam.getRcs() != null && techParam.getRcs().compareTo(BigDecimal.ZERO) > 0) {
            if (d.getRcsStripTempActAvg() != null) {
                //在±20范围内
                BigDecimal b1 = techParam.getRcs().subtract(BigDecimal.valueOf(20));
                BigDecimal b2 = techParam.getRcs().add(BigDecimal.valueOf(20));
                if (d.getRcsStripTempActAvg().compareTo(b1) < 0 || d.getRcsStripTempActAvg().compareTo(b2) > 0) {
                    d.setRcsStripTempActJudge(1);
                }
            } else {
                log.info("RCS指标参数不存在");
            }
        }
        //检查EQS符合度
        if (techParam.getEqs() != null && techParam.getEqs().compareTo(BigDecimal.ZERO) > 0) {
            if (d.getP9TempActAvg() != null) {
                //在±20范围内
                BigDecimal b1 = techParam.getEqs().subtract(BigDecimal.valueOf(20));
                BigDecimal b2 = techParam.getEqs().add(BigDecimal.valueOf(20));
                if (d.getP9TempActAvg().compareTo(b1) < 0 || d.getP9TempActAvg().compareTo(b2) > 0) {
                    d.setP9TempActJudge(1);
                }
            } else {
                log.info("EQS指标参数不存在");
            }
        }

        return true;
    }

    @Override
    public ResultData<String> importTechParam() {
        FileInputStream in = null;
        try {
            in = new FileInputStream("D:\\workspace\\项目文档\\生产工艺分析\\镀锌生产工艺分析\\工艺参数转存到库.xlsx");
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();

            for (int i = 1; i <= lastRowNum; i++) {
                XSSFRow row = sheet.getRow(i);
                double col0 = row.getCell(0).getNumericCellValue();
                String col1 = row.getCell(1).getStringCellValue();
                String col2 = row.getCell(2).getStringCellValue();
                String col3 = row.getCell(3).getStringCellValue();
                double col4 = row.getCell(4).getNumericCellValue();
                double col5 = row.getCell(5).getNumericCellValue();
                double col6 = row.getCell(6).getNumericCellValue();
                double col7 = row.getCell(7).getNumericCellValue();
                double col8 = row.getCell(8).getNumericCellValue();
                String col9 = row.getCell(9).getStringCellValue();
                TTechParam t = new TTechParam();
                t.setProNo(col0 + "");
                t.setProName(col1);
                t.setBrand(col2);
                t.setThickExec(col3);
                t.setRtf(BigDecimal.valueOf(col4));
                t.setScs(BigDecimal.valueOf(col5));
                t.setRcs(BigDecimal.valueOf(col6));
                t.setEqs(BigDecimal.valueOf(col7));
                t.setBaseValue(BigDecimal.valueOf(col8));
                t.setBaseValueOffset(col9);
                save(t);
            }
            excel.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return ResultData.ResultDataSuccess("success");
    }
}
